<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>登录 - 评论发表系统</title>
    <link rel="stylesheet" href="styles.css">
    <style>
        /* 自适应样式优化 */
        body {
            margin: 0;
            padding: 10px;
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
        }
        
        .container {
            width: 100%;
            max-width: 400px;
            margin: 0 auto;
            padding: 20px;
            box-sizing: border-box;
        }
        
        .form-group input {
            width: 100%;
            padding: 12px 16px;
            font-size: 16px;
            border: 2px solid #e1e8ed;
            border-radius: 8px;
            box-sizing: border-box;
        }
        
        @media (max-width: 480px) {
            .container {
                padding: 15px;
                max-width: 100%;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>🔐 用户登录</h1>
            <p>请登录后发表评论</p>
        </div>

        <div id="alertContainer"></div>

        <form id="loginForm">
            <div class="form-group">
                <label for="email">📧 邮箱地址</label>
                <input type="email" id="email" name="email" placeholder="请输入邮箱地址..." required autocomplete="username">
            </div>

            <div class="form-group">
                <label for="password">🔑 密码</label>
                <input type="password" id="password" name="password" placeholder="请输入密码..." required autocomplete="current-password">
            </div>

            <button type="button" class="submit-btn" onclick="handleLogin()">
                <div class="loading" id="loadingSpinner"></div>
                <span id="submitText">🚀 登录</span>
            </button>
        </form>
    </div>

    <script>
        const baseURL = 'http://172.20.10.2:8000/api/v1';

        async function handleLogin() {
            const email = document.getElementById('email').value.trim();
            const password = document.getElementById('password').value.trim();

            if (!email || !password) {
                showAlert('请输入邮箱和密码', 'error');
                return;
            }

            setLoading(true);

            try {
                // 第一步：验证用户信息
                console.log('第一步：验证用户信息...');
                const userResponse = await fetch(`${baseURL}/users/login`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        email: email,
                        password: password
                    })
                });

                if (!userResponse.ok) {
                    const errorData = await userResponse.json();
                    console.error('用户验证失败:', errorData);
                    throw new Error(errorData.detail || '用户名或密码错误');
                }

                const userData = await userResponse.json();
                console.log('用户验证成功:', userData);

                // 检查用户状态
                if (!userData.is_active) {
                    throw new Error('账户已被禁用');
                }

                showAlert('用户验证成功，正在获取访问令牌...', 'info');

                // 第二步：获取访问令牌
                console.log('第二步：获取访问令牌...');
                const formData = new FormData();
                formData.append('username', email);
                formData.append('password', password);

                const tokenResponse = await fetch(`${baseURL}/login/access-token`, {
                    method: 'POST',
                    body: formData
                });

                if (!tokenResponse.ok) {
                    const errorData = await tokenResponse.json();
                    console.error('获取令牌失败:', errorData);
                    throw new Error('获取访问令牌失败');
                }

                const tokenData = await tokenResponse.json();
                console.log('获取令牌成功:', tokenData.access_token ? 'Yes' : 'No');
                
                if (!tokenData.access_token) {
                    throw new Error('未获得访问令牌');
                }

                // 保存token和用户信息到localStorage
                localStorage.setItem('token', tokenData.access_token);
                localStorage.setItem('userInfo', JSON.stringify(userData));
                
                showAlert(`欢迎回来，${userData.full_name || userData.email}！正在跳转...`, 'success');
                
                // 延迟跳转到评论页面
                setTimeout(() => {
                    window.location.href = 'commentuploadimage.html';
                }, 1500);

            } catch (error) {
                console.error('Login error:', error);
                showAlert(error.message || '登录失败，请重试', 'error');
            } finally {
                setLoading(false);
            }
        }

        function setLoading(isLoading) {
            const submitBtn = document.querySelector('.submit-btn');
            const loadingSpinner = document.getElementById('loadingSpinner');
            const submitText = document.getElementById('submitText');
            
            submitBtn.disabled = isLoading;
            loadingSpinner.style.display = isLoading ? 'inline-block' : 'none';
            submitText.textContent = isLoading ? '登录中...' : '🚀 登录';
        }

        function showAlert(message, type = 'info') {
            const container = document.getElementById('alertContainer');
            const alert = document.createElement('div');
            alert.className = `alert ${type}`;
            alert.textContent = message;
            
            container.innerHTML = '';
            container.appendChild(alert);
            alert.style.display = 'block';
            
            if (type !== 'error') {
                setTimeout(() => {
                    alert.style.display = 'none';
                }, 3000);
            }
        }

        // 检查是否已经登录
        document.addEventListener('DOMContentLoaded', () => {
            const token = localStorage.getItem('token');
            if (token) {
                showAlert('您已登录，正在跳转...', 'info');
                setTimeout(() => {
                    window.location.href = 'commentuploadimage.html';
                }, 1000);
            }
        });

        // 回车键登录
        document.addEventListener('keypress', (e) => {
            if (e.key === 'Enter') {
                handleLogin();
            }
        });
    </script>
</body>
</html>
